<?php

/*
 * This file is part of fof/best-answer.
 *
 * Copyright (c) 2019 FriendsOfFlarum.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Plugin\XunSearch\Listeners;

use Flarum\Settings\Event\Saved;
use Plugin\XunSearch\Utils\XunSearchUtils;
use Flarum\Discussion\Discussion;
use Flarum\Post\Post;

class SaveOriginalDataToXunSearch
{

    /**
     * @var XunSearchUtils
     */
    protected $xunSearchUtils;

    public function __construct(XunSearchUtils $xunSearchUtils)
    {
        $this->xunSearchUtils = $xunSearchUtils;
    }

    public function handle(Saved $event)
    {
        if (!(isset($event->settings['xunsearch.index_server']) || isset($event->settings['xunsearch.search_server']))) {
            return;
        }

        $index = $this->xunSearchUtils->getIndex();
        $index->clean();
        $index->openBuffer(8);

        $discussions = Discussion::query()->where("hidden_at", null)->get();
        foreach ($discussions as $discussion) {
            $posts = Post::query()->where("hidden_at", null)
                ->where("discussion_id", $discussion->id)
                ->where("type", "comment")->get();

            foreach ($posts as $post) {
                $doc = $this->xunSearchUtils->getDocument($discussion, $post, $posts->count());
                $index->add($doc);
            }
        }

        $index->closeBuffer();
    }
}
